package com.example.chapter9_demo.controller;

import com.example.chapter9_demo.entity.Book;
import com.example.chapter9_demo.service.BookService;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/book")
public class BookController {

    @Autowired
    BookService bookService;

    @Resource
    CacheManager cacheManager;


    /*
     * 查询全部信息
     * */
    @GetMapping
    @Cacheable(value = "book",key = "#root.targetClass+'userlist'")
    public List<Book> getList() {
        return bookService.list();
    }

    /*
     * 查询单个信息
     * */
    @GetMapping("/{id}")
//    @Cacheable(value = "book",key = "#p0")
//    @Cacheable(value = "book",key = "#a0")
    @Cacheable(value = "book", key = "#id")
    public Book getById(@PathVariable Integer id) {
        return bookService.getById(id);
    }

    @GetMapping
    @Cacheable(value = "book", key = "#p0.id")
    public Book getBookBy(Book book) {
        return bookService.getById(book.getId());
    }

    @Cacheable(value = "book",key="#root.targetClass+'userlist'")
//    @Cacheable(value ={"book","book1"})
    public List<Book> getList2(){
        return bookService.list();
    }

    /*
     * 删除一本书的缓存
     * */
    @CacheEvict(value = "book", key = "#id") //根据参数指定的键来删除缓存
    @DeleteMapping("/{id}")
    public String deleteBook(@PathVariable Integer id) { //根据id号删除一本书, 同时删除缓存
        System.out.println("从数据库删除一本书，同时删除key为" + id + "的缓存");
//        bookService.removeById(id);
        return "删除成功";
    }


    /*
     * 修改信息
     * */
    @PutMapping
    @Caching(
            put = @CachePut(value = "book", key = "#book.id"),
            evict = @CacheEvict(value = "book", key = "#root.targetClass+'userlist'")
    )
    public Book updateBook(@RequestBody Book book) { //修改一本书
        System.out.println("从数据库修改一本书，同时修改缓存，key为" + book.getId());
        bookService.saveOrUpdate(book);
        return book;
    }
}
